<!-- 参数列表 -->
<template>
   <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 页头警告 -->
            <el-alert
                title="注意negro"
                type="warning"
                :closable="false"
                show-icon
                class="alert">
            </el-alert>
            <!-- 选择商品分类 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类: </span>
                    <!-- 选择商品分类的级联选择器 -->
                    <el-cascader
                        v-model="selectedKeys"
                        :options="cateList"
                        :props="{ 
                            expandTrigger: 'hover',
                            value: 'cat_id',
                            label: 'cat_name',
                            children: 'children'
                        }"
                        @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- 动态/静态参数tab -->
            <el-tabs v-model="activeName" 
                     @tab-click="handleClick"
                     class="tabs">
                <!-- 动态参数 -->
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数按钮 -->
                    <el-row :gutter="20">
                        <el-col :span="4">
                            <el-button type="primary" @click="showAddParamDialog" :disabled="isdisabled">添加参数</el-button>
                        </el-col>
                    </el-row>
                    <!-- 表格 -->
                    <el-table
                        :data="ParamList"
                        border
                        stripe
                        style="width: 92%">
                        <el-table-column type="expand">
                            <template slot-scope="scope"> 
                                <!-- 循环渲染tags -->
                                <el-tag 
                                    v-for="(item,index) in scope.row.attr_vals" 
                                    :key="index"
                                    closable
                                    @close="handleClose(scope.row, index)">{{item}}</el-tag>
                                <!-- new tag -->
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#" ></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称" ></el-table-column>
                        <el-table-column label="操作" width="330px">
                            <template slot-scope="scope">
                                <!-- 修改 -->
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyParamDialog(scope.row.attr_id)"></el-button>
                                <!-- 删除 -->
                                <template>
                                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="confirmDelete(scope.row.attr_id)"></el-button>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                <!--  -->
                </el-tab-pane>
                <!-- 静态属性 -->
                <el-tab-pane label="静态参数" name="only">
                    <!-- 添加参数按钮 -->
                    <el-row :gutter="20">
                        <el-col :span="4">
                            <el-button type="primary" @click="showAddParamDialog" :disabled="isdisabled">添加属性</el-button>
                        </el-col>
                    </el-row>
                    <!-- 表格 -->
                    <el-table
                        :data="attrList"
                        border
                        stripe
                        style="width: 92%">
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染tags -->
                                <el-tag 
                                    v-for="(item,index) in scope.row.attr_vals" 
                                    :key="index"
                                    closable>{{item}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#" ></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称" ></el-table-column>
                        <el-table-column label="操作" width="330px">
                            <template slot-scope="scope">
                                <!-- 修改 -->
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyParamDialog(scope.row.attr_id)"></el-button>
                                <!-- 删除 -->
                                <template>
                                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="confirmDelete(scope.row.attr_id)"></el-button>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                <!--  -->
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog
            title="添加参数"
            :visible.sync="addParamDialogVisible"
            width="50%"
            @close="addParamDialogClose">
            <!-- 内容主体区 -->
            <el-form 
                :model="addForm" 
                :rules="addRules"
                ref="addFormRef"
                label-width="100px">
                <el-form-item label="动态参数" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addParamDialogVisible=false">取 消</el-button>
                <el-button type="primary" @click="addParam">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑参数对话框 -->
        <el-dialog
            title="修改动态参数"
            :visible.sync="modifyParamDialogVisible"
            width="50%"
            @close="modifyParamDialogClose">
            <!-- 内容主体区 -->
            <el-form 
                :model="modifyForm" 
                :rules="addRules"
                ref="modifyFormRef"
                label-width="100px">
                <el-form-item label="参数名称" prop="attr_name">
                    <el-input v-model="modifyForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="modifyParamDialogVisible=false">取 消</el-button>
                <el-button type="primary" @click="modifyParam">确 定</el-button>
            </span>
        </el-dialog>
   </div>
</template>

<script>
    export default {
        data () {
          return {
            // 商品分类
            cateList: [],
            // 动态参数列表
            ParamList: [],
            // 静态属性列表
            attrList: [],
            // 选中的商品
            selectedKeys: [],
            // 默认激活动态参数tab
            activeName: 'many',
            // 是否禁用添加参数按钮
            isdisabled: true,
            // 添加参数对话框
            addParamDialogVisible: false,
            // 添加参数数据
            addForm: {
                // 参数名称
                attr_name: ''
            },
            // 添加参数规则
            addRules: {
                // 分类名称的规则
                attr_name: [
                    {
                        required: true,
                        message: '不能为空',
                        trigger: 'blur'
                    }
                ]
            },
            // 编辑参数对话框
            modifyParamDialogVisible: false,
            // 编辑参数数据
            modifyForm: {
                // 参数名称
                attr_name: ''
            },
            // 参数id
            attrId: '',
            // new input tag
            // inputVisible: false,
            // inputValue: '',
          };
        },
        created() {
            this.getCateList()
        },
        methods: {
            // 获取商品分类
            getCateList: async function() {
                const {data: res} = await this.$http.get('categories')
                if (res.meta.status !== 200){
                    return this.$message.error('获取商品分类列表失败')
                }
                this.cateList = res.data
                this.getParamList()
                console.log('商品分类列表数据为：',this.cateList);
            },
            // 获取参数列表
            getParamList: async function() {
                if(this.cateId) {
                    const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}})
                    if(res.meta.status !== 200){
                        return this.$message.error('获取参数失败')
                    }
                    // 给每条参数添加自己的inputVisible和inputValue
                    // 将每条参数的attr_vals变成array
                    res.data.forEach(item => {
                        item.inputVisible = false,
                        item.inputValue = ''
                        if(item.attr_vals.length > 0){
                            item.attr_vals = item.attr_vals.split(" ")
                        }else{
                            item.attr_vals = []
                        }
                        if(this.activeName === 'many'){
                            this.ParamList.push(item)
                        }else if(this.activeName === 'only'){
                            this.attrList.push(item)
                        }else{
                            return
                        }
                    })
                    console.log('ParamList: ',this.ParamList);
                    console.log('attrList: ',this.attrList);
                    
                }
            },
            // 级联选择器选项改变时
            handleChange: function() {
                if(this.selectedKeys.length !== 3) {
                    this.$message.warning('只能选择三级分类')
                    this.selectedKeys = []
                    this.ParamList = []
                    this.attrList = []
                    this.isdisabled = true
                    return 
                }
                this.getParamList()
                this.isdisabled = false
                console.log('选中的商品为：',this.selectedKeys);
            },
            // 选择tab时触发
            handleClick: function() {
                this.getCateList()
            },
            // 展示添加参数对话框
            showAddParamDialog: function() {
                this.addParamDialogVisible = true
            },
            // 确认添加参数 
            addParam: function() {
                this.$refs.addFormRef.validate(async valid => {
                    if(!valid) return
                    const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`,
                    {
                        attr_name: this.addForm.attr_name,
                        attr_sel: this.activeName
                    })
                    if(res.meta.status !== 201) {
                    return this.$message.error('添加失败！')
                }
                })
                
                // this.getCateList()
                this.addParamDialogVisible = false
                this.$message.success('添加成功！')
            },
            // 关闭添加参数对话框
            addParamDialogClose: function() {
                this.$refs.addFormRef.resetFields()
            },
            // 展示编辑参数的对话框
            showModifyParamDialog: function(attr_id) {
                console.log('当前属性id是: ',attr_id);
                this.attrId = attr_id
                this.modifyParamDialogVisible = true
            },
            // 关闭编辑参数对话框
            modifyParamDialogClose: function() {
                this.$refs.modifyFormRef.resetFields()
            },
            // 确认编辑参数
            modifyParam: function() {
                this.$refs.modifyFormRef.validate(async valid => {
                    if(!valid) return 
                    const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.attrId}`,
                    {
                        attr_name: this.modifyForm.attr_name,
                        attr_sel: this.activeName
                    })
                    if(res.meta.status !== 200){
                        return this.$message.error('编辑失败')
                    }
                    this.getCateList()
                    this.modifyParamDialogVisible = false
                    this.$message.success('编辑成功')
                })
            },
            // 确认删除参数
            confirmDelete: async function(attrId) {
                const confirmResult= await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                })
                if(confirmResult === 'confirm') {
                    const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
                    if(res.meta.status !== 200){
                        return this.$message.error('删除失败!')
                    }
                }
                this.getCateList()
                this.$message.success('删除成功!')
            },
            // 展示tag输入框
            showInput: function(row) {
                row.inputVisible = true
                // 当页面中的元素重新渲染之后，才会指定回调函数中的代码
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            // 确认添加new tag
            handleInputConfirm: async function(row) {
                // 如果输入框中的内容去掉空格后长度为0，说明是非法数据，应当清空
                if(row.inputValue.trim().length === 0){
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                }
                // console.log('row: ',row);
                row.attr_vals.push(row.inputValue.trim())
                const param = {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                }
                // console.log('param: ',param);
                const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, param)
                if(res.meta.status !== 200) {
                    return this.$message.error('添加属性失败！')
                }
                row.inputValue = ''
                row.inputVisible = false
                this.$message.success('添加成功！')
            },
            // 删除tag
            handleClose: async function(row,rmParamIndex) {
                row.attr_vals.splice(rmParamIndex, 1)
                const param = {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                }
                const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, param)
                if(res.meta.status !== 200) {
                    return this.$message.error('删除属性失败！')
                }
                this.$message.success('删除成功！')
            }
        },
        computed: {
            // 当前选中的三级分类的id
            cateId() {
                if(this.selectedKeys.length === 3){
                    return this.selectedKeys[2]
                }
                return null
            },
        }
    }

</script>
<style lang='less' scoped>
.alert {
    margin-bottom: 15px;
}
.tabs {
    margin-top: 15px;
}
.el-tag {
    margin: 10px;
}
.input-new-tag {
    width: 90px;
}
</style>